﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityFrameworkModel;

namespace CustomersFuctionality
{
    class CustomersFunctionality
    {
        static void PrintFirstFiveCustomers()
        {
            NorthwindEntities northwindEntities = new NorthwindEntities();
            var lastFiveCustomers =
                (from c in northwindEntities.Customers
                 orderby c.CustomerID
                 select c).Take(5);
            Console.WriteLine("Last 5 customers:");
            foreach (var customer in lastFiveCustomers)
            {
                Console.WriteLine("{0}. {1}", customer.CustomerID, customer.CompanyName);
            }
            Console.WriteLine();
        }
    
        static Customer GetCustomerById(NorthwindEntities northwindEntities, string customerId)
        {
            Customer customer = northwindEntities.Customers.FirstOrDefault(c => c.CustomerID == customerId);
            return customer;
        }

        static void InsertCustomer(string customerId, string companyName)
        {
            NorthwindEntities northwindEntities = new NorthwindEntities();
            Customer newCustomer = new Customer
            {
                CustomerID = customerId,
                CompanyName = companyName
            };
            northwindEntities.Customers.AddObject(newCustomer);
            northwindEntities.SaveChanges();
        }

        static void ModifyCustomer(string customerId, string newName)
        {
            NorthwindEntities northwindEntities = new NorthwindEntities();
            Customer c = GetCustomerById(northwindEntities, customerId);
            c.CompanyName = newName;
            northwindEntities.SaveChanges();
        }

        static void DeleteCustomer(string customerId)
        {
            NorthwindEntities northwindEntities = new NorthwindEntities();
            Customer c = GetCustomerById(northwindEntities, customerId);
            northwindEntities.Customers.DeleteObject(c);
            northwindEntities.SaveChanges();
        }

        static void Main()
        {
            PrintFirstFiveCustomers();

            InsertCustomer("APP", "APPLE");
            PrintFirstFiveCustomers();

            ModifyCustomer("APP", "APPLE Inc.");
            PrintFirstFiveCustomers();

            DeleteCustomer("APP");
            PrintFirstFiveCustomers();
        }

    }
}
